<template>
  <div class="to-upload" :class="{showNotAllowed}" @click="clickTip">

    <vi-upload
      :key="timeKey"
      @drop.native="drop"
      name="files"
      :multiple="true"
      :showUploadList="false"
      :action="uploadUrl"
      :headers="headers"
      :beforeUpload="beforeUpload"
      :disabledclick="disabledclick"
      @change="handleChange"
      @newChange="newChange"
      @dropTransition="dropTransition"
    >
      <slot>
        <vi-button type="primary" class="upload-list">
          <img id="add-file" src="../../assets/image/add_file.png" class="color-filter" alt>
          <span>添加文件</span>
        </vi-button>
      </slot>
    </vi-upload>

    <vi-modal
      title="添加文件"
      width="400px"
      class="upload-dialog"
      :visible="(visible && !screenShotsStatus)"
      :destroyOnClose="true"
      :maskClosable="false"
      @ok="handleOk"
      @cancel="handleCancel"
    >
      <div style="font-weight: 700;">
        请选择一个文件夹上传：
        <div class="folder-dialog">
          <div v-if="item.dirType !== 1" v-for="item in this.folderList" :key="item.id" style="margin-bottom: 3px;">
            <vi-checkbox
              :checked="item.chosen"
              @change="selectFold($event, item.id)"
            >
              <span style="font-weight: 500;">{{item.dirName}}</span>
            </vi-checkbox>
          </div>
        </div>
      </div>
    </vi-modal>

    <!--解密操作-->
    <vi-modal
    title="PDF解密"
    v-if="pdfPasswordModel"
    width="450px"
    :destroyOnClose="true"
    :maskClosable="false"
    :visible="pdfPasswordModel"
    okText="确定"
    class="identify-modal"
    @ok="pdfsPasswordSave"
    @cancel="pdfsPasswordCancel"
  >
    <div class="pdf-password-cont">
      <div class="password-title">选择的文件有密码，请输入密码</div>
      <div class="password-fileName">{{pdfPasswordData[pdfPasswordStep].fileName}}</div>
      <vi-input type="password" maxlength="50" placeholder="请输入密码" v-model="pdfPasswordData[pdfPasswordStep].value"></vi-input>
      <div class="pdf-password-tips" v-if="pdfPasswordData.length>1">
        <vi-checkbox :checked="pdfPasswordAll" @change="pdfPasswordAllChange">应用于所有文件</vi-checkbox>
      </div>
    </div>
  </vi-modal>
    <vi-modal
      title="识别上限"
      v-if="ocrResultMaxPagesStatus"
      width="450px"
      :destroyOnClose="true"
      :maskClosable="false"
      :visible="ocrResultMaxPagesStatus"
      :footer="null"
      class="identify-modal"
      @cancel="()=>{ocrResultMaxPagesStatus=false}"
      >
      <div class="pdf-ocr-max">
        <p>今天识别次数已到上限</p>
        <p>请更新识别助手版本或明天再试吧</p>
      </div>
      <div class="pdf-ocr-btnW">
        <vi-button type="primary" @click="()=>{ocrResultMaxPagesStatus=false}">确定</vi-button>
      </div>
    </vi-modal>
  </div>
</template>

<script>
import { baseURL } from "../../libs/http.js";
import activeShowMixin from "../../mixin/activeShow.mixin";

import _ from 'lodash';
import $ from 'jquery';

export default {
  name: "upload",
  mixins: [activeShowMixin],
  props: {
    disabledclick: {
      type: Boolean,
      default: false
    },
    showNotAllowed: {
      type: Boolean,
      default: true
    },
    uploadId: {
      type: String,
      default: false
    }
  },
  data() {
    return {
      headers: {
        authorization: "authorization-text"
      },
      accept: ".jpg,.jpeg,.png,.bmp,.tif,.tiff,.pdf",
      mesTips: false, // 上传中提示框判定(避免多个提示框)
      timeKey: '', // 上传key
      uploadTotal: 0, // 当前上传文件总数
      visible: false,
      folderSelected: false, // 控制是否禁用上传
      hasId: false, // 是否勾选了文件夹
      dropUpload: false, // 是否是托人上传，并且需要弹窗选择
      dropFun: null, // 上传的方法
      dropFile: null, // 上传的文件
      pdfPasswordModel: false, // 加密的pdf文件进行解密操作
      pdfPasswordData: [], // 需要进行输入密码的数组储存
      pdfPasswordStep: 0, // 输入密码进行步数
      pdfPasswordAll: true, //是否应用所有文件
      ocrResultMaxPagesStatus: false, // 识别是否达到上限
    };
  },
  methods: {
    /**
     * NOTE:
     * - 拖拽上传，不会调用beforeUpload函数
     * - 使用原生drop进行文件格式校验，并给出提示
     * - 目前添加全局拖拽了，这里不需要额外增加拖拽上传了
     */
    drop(e) {

      // 将弹窗收起
      this.setFileSearchVisible(false);
      this.setSelectionBtnVisible(false);
      this.setCaptureVisible(false);
      this.setExportVisible(false);
      this.setFileDownloadVisible(false);
      this.setQaVisible(false);

      e = e || window.event;
      e.stopPropagation();
      // if(this.editMode){
      //   this.$message.warn("编辑模式不支持文件上传！");
      //   return false;
      // }
      // console.log( 'drop', e);
    },
    clickTip(e) {
      if ( this.disabledclick ) return
      // debugger
      if (this.allSelectedFolderList.length === 1) {
        this.setDirId(this.allSelectedFolderList[0])
        return
      }
      if (!this.folderSelected) {
        this.visible = true;
        e = e || window.event;
        e.stopPropagation();
        e.preventDefault();
      }
      this.folderSelected = false;
    },
    newChange(file, msg) {
      // console.log('newChange', file, msg);

      if(msg.type){
        this.$message.warn(`不支持的文件类型，请上传${this.accept}文件！`);
      }
      else if(msg.size){
        this.$message.warn("图片单个文件最大支持20MB！");
      }
      else if(msg.sizePdf){
        this.$message.warn("PDF单个文件最大支持200MB！");
      }

      if(file.length>0){
        this.setLoadingLabel(`正在上传（0/${file.length}）`);
        this.uploadTotal = file.length;
      }
    },
    beforeUpload(file, fileList) {
      let time = 0;
      if(fileList.length > 50){
        fileList.map( (v,i) => {
          if(v.uid == file.uid){
            time = i>50 ? Math.floor( i / 50 )*1000 : 0
          }
        } )
      }

      // console.log('beforeUpload', file, fileList, time );
      setTimeout(() => {
        return true;
      }, time);
    },
    handleChange(info) {
      // console.log( 'handleChange info', info, info.fileList, this.$store.state.file.fileListActive.length );
      let fileList = _.cloneDeep(info.fileList);
      // console.log( 'info.fileList', fileList.filter( v => v.status == "uploading" ).length, fileList.filter( v => v.status !== "uploading" ).length );
      if( fileList.filter( v => v.status == "uploading" ).length == 0 && info.fileList.length == this.uploadTotal ){
        // this.setFileListActive([]); // 太耗内存了
        this.pdfPasswordData = fileList.filter(item => item.response.state.ok === 900).map(item => {return {fileId: item.response.body, fileName: item.name, value: ''}}); // 处理加密数据
        this.ocrResultMaxPagesStatus = Boolean(fileList.filter(item => item.response.state.ok === 1303).length); // 处理最大识别页码

        if(this.pdfPasswordData.length>0){
          this.pdfPasswordModel = true
          this.pdfPasswordStep = 0
          this.pdfPasswordAll = true
        }else{
          this.setNeedRefreshList(true);
        }

        this.setFileLoadingState(false);

        setTimeout(() => {
          this.setLoadingLabel('');
          this.uploadTotal = 0;
          this.timeKey = (new Date()).valueOf();
          this.dropUpload = false;
          this.dropFun = null;
          this.dropFile = null;
        }, this.uploadTotal>50?500:100);

        console.log('关闭', this.timeKey, );
      }
      else{
        let str = `正在上传（${fileList.filter( v => v.status !== "uploading" ).length}/${this.uploadTotal}）`;
        if( this.$store.state.status.loadingLabel !== str && this.uploadTotal !== 0 ){
          this.setLoadingLabel(str);
          // this.setFileListActive(fileList); // 太耗内存了
        }
      }

      let status = false
      if(info.event){
        if(info.event.timeStamp){
          status = true
        }
      }
      if(status){
        return
      }

      try {
        // 上传中
        if (info.file.status == "uploading") {
          if (this.mesTips == false) {
            // this.$message.loading("正在上传..", 0);
            this.mesTips = true;
            this.setFileLoadingState(true);
          }
        }
        // 上传成功
        if (info.file.status === "done") {
          this.$message.destroy();
          this.mesTips = false;

          if (!info.file.response.state.ok) {
            this.$message.error(`服务异常，${info.file.name} 上传失败，请重新上传！`);
            return false;
          }

          if (info.file.response.state.ok === 1004) {
            this.$message.warning(`上传失败：${info.file.response.state.failed}！`);
            return false;
          }
        }
        // 上传失败
        else if (info.file.status === "error") {
          // console.log("上传服务异常");
          this.$message.destroy();
          this.$message.error(`服务异常，${info.file.name} 上传失败，请重新上传！`);
          this.mesTips = false;

        }
        //
      }
      catch (error) {
          // console.log(error);
      }

    },
    // 拖入上传 过渡
    dropTransition(fun, file) {
      // console.log( 'dropTransition', fun, file);
      if(file.length === 0){
        return
      }

      // 需要弹窗选择上传
      if (this.dirId === 'KWJJ'){
        // fun(file);
        this.dropUpload = true;
        this.dropFun = fun;
        this.dropFile = file;

        this.visible = true;
      }
      // 正常上传
      else{
        fun(file);
        return false;
      }
    },
    handleOk () {
      // debugger
      if (this.hasId) {
        // 托人弹窗选择
        if(this.dropUpload){
          this.dropFun(this.dropFile);
        }
        else{
          this.folderSelected = true;
          let selector = this.uploadId + ' input:hidden';
          // console.log(selector)
          // console.log(this.folderList)
          $(selector)[0].click();
        }

        this.visible = false;
      }
      else {
        this.$message.warn('请选择一个文件夹！');
        this.dropUpload = false;
        this.dropFun = null;
        this.dropFile = null;
        return
      }

      this.hasId = false;
      this.folderList.forEach(item => {
        item.chosen = false;
      })

    },
    handleCancel () {
      this.folderSelected = false;
      this.visible = false;
      this.hasId = false;
      this.dropUpload = false;
      this.dropFun = null;
      this.dropFile = null;
      this.folderList.forEach(item => {
        item.chosen = false;
      })
    },
    // 选择文件夹
    selectFold(e, id) {
      this.hasId = false;
      // if (e.target.checked) {
      //   console.log(id)
      //   this.setDirId(id);
      //   this.hasId = true;
      //   console.log(this.dirId)
      // }
      this.folderList.forEach(item => {
        if (item.id === id) {
          item.chosen = !item.chosen;
          if (item.chosen) {
            // console.log(id)
            this.setDirId(id);
            this.hasId = true;
            // console.log(this.dirId)
          }
        } else {
          item.chosen = false;
        }
      })
    },
    pdfsPasswordSave(){
      if(this.pdfPasswordAll) {
        let $password = encodeURIComponent(this.pdfPasswordData[this.pdfPasswordStep].value)
        this.pdfPasswordData.filter(item=>!item.deal).map(({fileId, fileName}) => {
          let url = `${this.$url.setPdfpassword.url}/${fileId}?password=${$password}`,
            urlObj = this.$url.setPdfpassword;
          this.$http({ ...urlObj, url: url }).then(({state})=>{
            if(state.ok === 901){
              this.$message.warning(`${fileName}:${state.failed}`);
            }
            if(this.pdfPasswordData.length-1 === this.pdfPasswordStep){
              this.pdfPasswordModel = false
              this.setNeedRefreshList(true);
              return;
            }
            this.pdfPasswordStep ++
          })
        })
      }else{
        let $password = encodeURIComponent(this.pdfPasswordData[this.pdfPasswordStep].value)
        let url = `${this.$url.setPdfpassword.url}/${this.pdfPasswordData[this.pdfPasswordStep].fileId}?password=${$password}`,
          urlObj = this.$url.setPdfpassword;
        this.$set(this.pdfPasswordData[this.pdfPasswordStep],'deal',true);
        this.$http({ ...urlObj, url: url }).then(({state})=>{
          if(state.ok === 901){
            this.$message.warning(`${this.pdfPasswordData[this.pdfPasswordStep].fileName}:${state.failed}`);
          }
          if(this.pdfPasswordData.length-1 === this.pdfPasswordStep){
            this.pdfPasswordModel = false
            this.setNeedRefreshList(true);
            return;
          }
          this.pdfPasswordStep ++
        })
      }
    },
    pdfsPasswordCancel(){
      let url = `${this.$url.getRecognize.url}/${this.pdfPasswordData[this.pdfPasswordStep].fileId}/pages?pageIndex=`,
        urlObj = this.$url.getRecognize;
      this.$http({ ...urlObj, url: url })
      if(this.pdfPasswordData.length-1 === this.pdfPasswordStep){
        this.pdfPasswordModel = false
        this.setNeedRefreshList(true);
      }
      this.pdfPasswordStep ++
    },
    pdfPasswordAllChange(){
      this.$set(this,'pdfPasswordAll',!this.pdfPasswordAll)
    },
  },
  watch: {
    visible(newVal) {
      if(newVal){
        // 默认勾选第一个
        this.folderList.map( v =>{
          if(v.dirName === '我的文件夹'){
            this.selectFold(null, v.id);
          }
        } );
      }
      else{
        // 至空
        this.hasId = false;
        this.folderList.forEach(item => {
          item.chosen = false;
        });
      }
    },
  },
  computed: {
    uploadUrl() {
      return `${baseURL}${this.$url.uploadFile.url}/${this.userId}/${
        this.dirId
      }`;
    },
    dirId() {
      return this.$store.state.user.dirId;
    },
    userId() {
      return this.$store.state.user.userId;
    },
    fileListActive() {
      return this.$store.state.file.fileListActive;
    },
    folderList() {
      return this.$store.state.file.folderList;
    },
    screenShotsStatus() {
      return this.$store.state.status.screenShotsStatus;
    },
    allSelectedFolderList() {
      return this.$store.state.file.allSelectedFolderList;
    },
    // editMode() {
    //   return this.$store.state.status.editMode;
    // }
  }
};
</script>

<style lang="less">
.to-upload {
  overflow: hidden;
  height: calc(100% - 47px);

  &>span {
    display: inline-block;
    width: 100%;
    height: 100%;
  }

  .ant-btn {
    display: flex;
    align-items: center;
  }

  img {
    margin-right: 8px;
  }
}

.upload-list,
.upload-list:hover,
.upload-list:active,
.upload-list:focus {
  background-color: @primary !important;
  color: #fff !important;
  border-color: @primary !important;
}
.not-allowed #add-file {
  content: url('../../assets/image/add_file_disabled.png')
}

.folder-dialog {
  max-height: 150px;
  margin-top: 10px;
  overflow: auto;
  .ant-checkbox + span {
    width: 322px;
    vertical-align: text-top;
  }
}

// .upload-dialog {
//   width: auto !important;
//   max-width: 580px;
// }

.upload-dialog .ant-modal-body {
  padding: 20px 24px 0;
  -webkit-user-select:none;
  -moz-user-select:none;
  -ms-user-select:none;
  user-select:none;
}

.pdf-password-cont{
  padding: 0 50px;
  color: #090e21;
  .password-title{
    font-size: 16px;
    margin-bottom: 15px;
  }
  .password-fileName{
    font-size: 14px;
    margin-bottom: 10px;
  }
  .pdf-password-tips{
    font-size: 12px;
    color: #9095a3;
    margin-top: 10px;
  }
}

.pdf-ocr-max{
  padding: 50px 60px;
  font-size: 16px;
  color: #090e21;
  text-align: center;
  user-select: none;
}
.pdf-ocr-btnW{
  text-align: center;
}

</style>
